var params = {
    target: "web"
}

var player = new QMplayer(params);

//请求songid
var songid = [];
var playmid;

$.ajax({
    sync:false,
    type: 'POST',
    data: 'json',
    url: '/musiclist',
    success: function (result) {
        result.forEach(function(item){
            songid.push({
                songid:item.songid,
                songstate:item.state
            });
        })
        //初始播放音乐mid在数组中的位置
        setTimeout(() => {
            playmid = Math.floor(Math.random() * songid.length - 1);
            //第一次点击页面开始播放音乐（Chromium、WebKit等内核不再支持自动播放）
            var autoplay = true;
            $(window).one('click', function () {
                player.playReady();
                setTimeout(() => {
                    player.play(songid[playmid].songid);
                }, 1000)

                autoplay = false;
            })
        })
    }
});
//报错状态标记
function state(state,songid){
    $.ajax({
        type: 'POST',
        data: 'json',
        url: '/musicerror',
        data:{
            state:state,
            songid:songid,
        }
    });
}



//初始音量50%
$("audio")[0].volume = 0.5;

//播放/暂停按钮图标匹配播放状态
function iconswitch(){
    player.state == 'playing'
    ? 
    //播放
    $('#toggle').addClass('fa-pause').removeClass('fa-play').css('padding', '0.04rem 0 0 0.02rem')
    : 
    //暂停
    $('#toggle').addClass('fa-play').removeClass('fa-pause').css('padding', '0.04rem 0 0 0.1rem');
}
player.on("play", function () {
    iconswitch();
})
player.on("pause", function () {
    iconswitch();
})

//播放/暂停
function toggle(){
    if(autoplay==false){
        player.toggle();
    }
}

//播放上一首
function playPrev(){
    playmid -= 1;
    playmid < 0 ? playmid = songid.length-1 : '';
    player.play(songid[playmid].songid);
}
//播放下一首
function playNext(){
    playmid += 1;
    playmid >= songid.length?playmid = 0 : '';
    player.play(songid[playmid].songid);
}
//自动切换下一首
player.on("ended", function () {
    playNext();
    iconswitch();
})

//无法播放误报检测
player.on("play", function () {
    state('0', player.data.song.id);
})

//错误自动切歌/报错标记
player.on("error", function () {
    state('1',player.data.song.id);
    playNext();
    iconswitch();
})

//音量滑块
//初始化滑块
function initializeRange(){
    $("#volumeRange").val(100 - ($("audio")[0].volume * 100));
}

function VolumeSet() {
    $("audio")[0].volume = (100-$("#volumeRange").val()) / 100;
    $("#volumeRange").css('background-size', (100 - ($("audio")[0].volume * 100)) + '% 100%');

    $("audio")[0].volume == 0?
    $("#volumeMin").removeClass('fa-volume-down').addClass('fa-volume-mute'):
    $("#volumeMin").removeClass('fa-volume-mute').addClass('fa-volume-down');
}
//音量最大
function VolumeMax(){
    $("#volumeRange").val('0');
    VolumeSet();
}
//音量最小
function VolumeMin() {
    $("#volumeRange").val('100');
    VolumeSet()
}
